<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use app\admin\model\UserIdentity as user_identity_info;

class Basic extends Controller
{

    /**
     * 初始化方法，所有子类继承
     */
    protected function _initialize()
    {
        $token = input('token');
        if ($token != encryption(config('token'))) {
            json_fail([
                'status' => -10,
                'msg' => '登陆验证失败'
            ]);
        }
    }


    /**
     * 默认请求
     */
    public function index()
    {

    }


    /**
     * @param $type
     * @param string $id
     * @return string
     * @throws \Exception
     *   生成信息二维码
     */
    public function get_video_code($type, $id = '')
    {

        // $type  1 视频  2 个人信息
        if ($type == 1) {
            $path = '';
        } else if ($type == 2) {
            $path = '';
        }
        //实例化数据库
        $token = Db('wx_token')->limit(1)->value('access_token');
        //获取 二维码
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $token;
        //跳转页面
        $data = array(
            'path' => $path
        );
        $code = json_encode($data);
        $imgInfo = $this->api_notice_increment($url, $code);
        $local = 'static/Code/' . date('YmdHis') . rand(1221212, 1212012102102) . '.png';
        file_put_contents($local, $imgInfo);
        sleep(3);
        $code_url = $this->upImg($local);

        if ($type == 2) {
            // 直接存 用户表
            $data['code_url'] = $code_url;
            $user_identity_info = new user_identity_info();
            $user_identity_info->allowField(true)->save($data, ['id' => $id]);
        } else if ($type == 1) {
            return $code_url;
        }

    }


    /**
     * @param $filePath
     * @return string
     * @throws \Exception
     * 上传 七牛云照片
     */
    public function upImg($filePath)
    {
        Vendor('Qiniusdk.autoload');
        $auth = new Auth(config('accessKey'), config('secretKey'));
        $token = $auth->uploadToken(config('bucket'));
        $key = 'result' . time() . 'ok';
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        return config('domain') . $key;
    }


    /**
     * @param $uid
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查询管理员身份信息
     */
    public function search_manager_info($uid)
    {
        $system_manager = Db('system_manager');
        $identity = $system_manager->where(array('id' => $uid))->find();
        if ($identity) {
            return $identity;
        }
    }

    /**
     *  获取所有菜单
     */
    public function getAllMenu()
    {
        $system_manager = Db('system_manager');
        //查询admin表的role_id
        $uid = input('post.user_id');
        $token = input('post.token');
        if (!$uid) {
            json_fail(data('-1', '用户id不能为空!'));
        }
        // $token =  'b5c33d55a95eceb74853f0b08b08b6b887d2c8dd';
        if (!$token) {
            json_fail(data('-2', 'token不能为空!'));
        }
        //        b5c33d55a95eceb74853f0b08b08b6b887d2c8dd
        $user_id = decode($uid);
        //        dd($user_id);    MDAwMDAwMDAwMIGEbXY
        //$user_id = 1;
        if (!$user_id) {
            json_fail(data('-4', '用户id解密失败!'));
        }
        if ($token == encryption(config('token'))) {
            $new_menu = Db('new_menu');
            //           查询用户权限
            $identity = $system_manager->where(array('id' => $user_id))->value('identity');
            //  $identity = 4;
            if ($identity == 1) {
                $map = array(
                    'pid' => 0,
                    'status' => 1
                );
//                 $map_two['id'] =['not in',[42,35]];->where($map_two)
                $info = $new_menu->where($map)->field('name,icon,id,url')->where('id', 'neq', 57)->order('sort asc')->select();
                $list = $this->getMenu($info);
            } else if ($identity == 2) {
                $map = array('id' => 42);
                $info = $new_menu->where($map)->where('status', 1)->field('name,icon,id,url')->order('sort asc')->select();
                //   $list = $this->getMenu($info);
                $map_two['id'] = ['not in', [44, 45, 56]];
                foreach ($info as $k => $v) {
                    $v['child'] = Db('new_menu')->where($map_two)->where(array('pid' => $v['id'], 'status' => 1))->field('name,url')->order('sort asc')->select();
                    if ($v['child']) {
                        $info[$k] = $v;
                    }
                }
                $list = $info;
            } else if ($identity == 3) {
                $map = array('id' => 42);
                $info = $new_menu->where($map)->where('status', 1)->field('icon,name,id,url')->order('sort asc')->select();
                //$list = $this->getMenu($info);
                $map_two['id'] = ['not in', [43, 45, 56]];
                foreach ($info as $k => $v) {
                    $v['child'] = Db('new_menu')->where($map_two)->where(array('pid' => $v['id'], 'status' => 1))->field('name,url')->order('sort asc')->select();
                    if ($v['child']) {
                        $info[$k] = $v;
                    }
                }
                $list = $info;
            } else if ($identity == 4) {
                $map = array('id' => 35);
                $info = $new_menu->where($map)->where('status', 1)->field('icon,name,id,url')->order('sort asc')->select();
                $list = $this->getMenu($info);
            } else if ($identity == 5) {
                $map = array('id' => 57);
                $info = $new_menu->where($map)->where('status', 1)->field('icon,name,id,url')->order('sort asc')->select();
                $list = $this->getMenu($info);
            }
            json_success($list);
        } else {
            json_fail(data('-3', 'token验证错误!'));
        }
    }


    /**
     * @param $url
     * @param $data
     * @return mixed
     * 生成二维码
     */
    public function api_notice_increment($url, $data)
    {
        $ch = curl_init();
        $header = array("Accept-Charset: utf-8");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        return $tmpInfo;
    }


    //公用菜单
    public function getMenu($info)
    {
        foreach ($info as $k => $v) {
            $v['child'] = Db('new_menu')->where(array('pid' => $v['id'], 'id' => array('neq', 67), 'status' => 1))->field('name,url')->order('sort asc')->select();
            if ($v['child']) {
                $info[$k] = $v;
            }
        }
        return $info;
    }

    /**
     * 获取from_id
     */
    public function getFromId($user_id)
    {
        $user_from_id = Db('userFormid');
        //修改之前过期的from_id
        $from_id = $user_from_id->where(array('user_id' => $user_id, 'status' => 2))->order('id asc')->value('form_id');
        return $from_id;
    }


    /**
     * 上传-单张图片
     * @param $file
     * @param $folder
     * @return string
     * @author jihaichuan
     */
    protected function upload_single_img($file, $folder)
    {
        // 移动到框架应用根目录/uploads/ 目录下
        $root = '.';
        $path = '/uploads/' . $folder . '/';
        $info = $file->move($root . $path);
        if (!$info) {
            json_fail([
                'status' => -12,
                'msg' => '上传文件失败！'
            ]);
        }

        // 获取文件上传的路径
        return config('site_url') . $path . $info->getSaveName();
    }


    /**
     * 上传多张图片，功能
     * @param $files
     * @param $folder
     * @return array
     * @author jihaichuan
     */
    protected function upload_multi_img($files, $folder)
    {
        // 移动到框架应用根目录/uploads/ 目录下
        $root = '.';
        $path = '/uploads/' . $folder . '/';
        $imgs = [];
        foreach ($files as $file) {
            $info = $file->move($root . $path);
            if (!$info) {
                json_fail([
                    'status' => -12,
                    'msg' => '上传文件失败！'
                ]);
            }

            // 获取文件上传的路径
            $imgs[] = config('site_url') . $path . $info->getSaveName();
        }

        // 返回上传图片数组
        return $imgs;
    }


    /**
     * @param $url
     * @param $id
     * @param $name
     * @return string
     * 生成普通带参数的二维码
     */
    public function get_qr_code($url, $id, $name)
    {
//        //带LOGO
//         $errorCorrectionLevel = 'L';//容错级别
//         $matrixPointSize = 9;//生成图片大小
//         //生成二维码图片
//         Vendor('phpqrcode.phpqrcode');
//         $object = new \QRcode();
//         $ad = 'static/Qrcode/'.$id.$name.'.jpg';
//         $object->png($url, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
//         $logo = 'static/Image/logo1.jpg';//准备好的logo图片
//         $QR = 'static/Qrcode/'.$id.$name.'.jpg';//已经生成的原始二维码图
//
//         if ($logo !== FALSE) {
//           $QR = imagecreatefromstring(file_get_contents($QR));
//           $logo = imagecreatefromstring(file_get_contents($logo));
//           $QR_width = imagesx($QR);//二维码图片宽度
//           $QR_height = imagesy($QR);//二维码图片高度
//           $logo_width = imagesx($logo);//logo图片宽度
//           $logo_height = imagesy($logo);//logo图片高度
//           $logo_qr_width = $QR_width / 5;
//           $scale = $logo_width/$logo_qr_width;
//           $logo_qr_height = $logo_height/$scale;
//           $from_width = ($QR_width - $logo_qr_width) / 2;
//           //重新组合图片并调整大小
//           imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
//           $logo_qr_height, $logo_width, $logo_height);
//         }
//         //输出图片  带logo图片
//         imagepng($QR, 'static/Qrcode/'.$id.$name.'.jpg');
        //不带LOGO
        Vendor('phpqrcode.phpqrcode');
        //生成二维码图片
        $object = new \QRcode();
        $level = 3;
        $size = 4;
        $ad = 'static/Qrcode/' . $id . $name . '.jpg';
        $errorCorrectionLevel = intval($level);//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        $object->png($url, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
        return '/static/Qrcode/' . $id . $name . '.jpg';
    }


    /**
     *
     * 获取access_token
     */
    public function get_access_token()
    {
        $wxtoken = Db('wx_token');
        $map = array(
        	'wxatid' => config('xiaocx_app_id')
		);
        $token = $wxtoken->where($map)->value('access_token');
        if (!$token) {
            $token = 0;
        }
        return $token;
    }


    /**
     * @param $path
     * @param string $id
     * @return string
     * @throws \Exception
     * 生成小程序码并上传至七牛云
     */
    public function get_code($path, $id)
    {

        //实例化数据库
        $token = Db('wx_token')->limit(1)->value('access_token');
        //获取 二维码
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $token;
        //跳转页面
        $data = array(
            'path' => $path.'?channel_id='.$id
        );
        $code = json_encode($data);
        $imgInfo = $this->api_notice_increment($url, $code);
        $local = 'static/Code/' . date('YmdHis') . rand(1221212, 1212012102102) . '.png';
        file_put_contents($local, $imgInfo);
        sleep(3);
        $code_url = $this->upImg($local);
        return $code_url;
    }


    /**
     * @param $touser
     * @param $template_id
     * @param $form_id
     * @param $data
     * @param $url
     * @return mixed|string
     * 发送模板消息
     */
    public function sendTemplatel($touser, $template_id, $form_id, $data, $url)
    {
        $dataInfo = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'form_id' => $form_id,
            'data' => $data
        );
        if ($url) {
            $dataInfo['page'] = $url;
        }
        $submitData = json_encode($dataInfo);
        //实例化表
        $wxtoken = Db('WxToken');
        $token = $wxtoken->where('wxatid', config('xiaocx_app_id'))->value('access_token');

        $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token;
        $info = http_curl($url, 'post', $submitData);
        return $info;
    }

    /**
     * @param $error_code
     * @return string
     * 微信错误码
     */
    public function error_code($error_code){
        if(!$error_code){
            json_fail('获取错误码失败');
        }
        $text='';
        switch ($error_code){
            case 40037:
                $text='模板id不正确';
                break;
            case 41028:
                $text='form_id过期或者不正确';
                break;
            case 41029:
                $text='form_id已被使用';
                break;
            case 41030:
                $text='page不正确';
                break;
            case 45009:
                $text='接口调用超过限额';
                break;
            case 40003:
                $text='open_id错误';
                break;
            case 40013:
                $text='appid不正确';
                break;
            case 42001:
                $text='access_token 过期';
                break;
        }
        return $text;
    }

     /**
     * @param int $length
     * @return string
     * 格式化数字显示
     */
    public static function formatNum($num=0)
    {
        if($num<10000) {
            return $num;
        } elseif ($num>=10000&&$num<100000000) {
            return round($num/10000,2).'万';
        } else {
            return round($num/100000000,2).'亿';
        }
    }

    
}